/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ar.com.transporte.bean;

import ar.com.transporte.dao.imp.UsuarioDaoImp;
import ar.com.transporte.dominio.Usuario;
import ar.com.transporte.util.EncodeMD;
import ar.com.transporte.util.JsfUtil;
import ar.com.transporte.util.PaginationHelper;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;

/**
 *
 * @author Daniela
 */
public class UsuarioController {

    /**
     * Creates a new instance of UsuarioController
     */

    private Usuario current;
    private DataModel items = null;
    private PaginationHelper pagination;
    private int selectedItemIndex;

    UsuarioDaoImp usuario = new UsuarioDaoImp();
    
    public UsuarioController() {
    }

    public Usuario getSelected() {
        if (current == null) {
            current = new Usuario();
            selectedItemIndex = -1;
        }
        return current;
    }


    public PaginationHelper getPagination() {
        int numeroRegistros = 10;
        if (pagination == null) {
            pagination = new PaginationHelper(numeroRegistros) {

                @Override
                public int getItemsCount() {
                    return usuario.getUsuarioCount();
                }

                @Override
                public DataModel createPageDataModel() {
                    return new ListDataModel(usuario.getAll(getPageSize(), getPageFirstItem()));
                    
                }
            };
        }
        return pagination;
    }

    public String prepareList() {
        recreateModel();
        return "list";
    }

    public String prepareView() {
        current = (Usuario) getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        return "View";
    }

    public String prepareCreate() {
        current = new Usuario();
        selectedItemIndex = -1;
        return "new";
    }

    public String create() {
        try {
            current.setPassword(EncodeMD.getStringMessageEncripted(current.getPassword(),EncodeMD.MD5));
            usuario.insert(current);
            JsfUtil.addSuccessMessage("Usuario Creado Satisfactoriamente");
            return prepareCreate();
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, "Error: ");
            return null;
        } 
    }

    public String prepareEdit() {
        current = (Usuario) getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        return "edit";
    }


    public String update() {
        try {
            if(!usuario.getItem(current.getId()).getPassword().equals(current.getPassword())){
                current.setPassword(EncodeMD.getStringMessageEncripted(current.getPassword(),EncodeMD.MD5));                            
            }
            usuario.update(current);
            return prepareList();
        } catch (Exception e) {
            return null;
        } 
    }

    public String destroy() {
        current = (Usuario) getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        performDestroy();
        recreatePagination();
        recreateModel();
        return "list";
    }

//    public String destroyAndView() {
//        performDestroy();
//        recreateModel();
//        updateCurrentItem();
//        if (selectedItemIndex >= 0) {
//            return "View";
//        } else {
//            recreateModel();
//            return "List";
//        }
//    }

    private void performDestroy() {
        try{
            usuario.delete(current);                      
        }catch(Exception e){}
    }

    private void updateCurrentItem() {
//        int count = getJpaController().getUsuariosCount();
//        if (selectedItemIndex >= count) {
//            // selected index cannot be bigger than number of items:
//            selectedItemIndex = count - 1;
//            // go to previous page if last page disappeared:
//            if (pagination.getPageFirstItem() >= count) {
//                pagination.previousPage();
//            }
//        }
//        if (selectedItemIndex >= 0) {
//            current = getJpaController().findUsuariosEntities(1, selectedItemIndex).get(0);
//        }
        
    }

    public DataModel getItems() {
        if (items == null) {
            items = getPagination().createPageDataModel();
        }
        return items;
    }

    private void recreateModel() {
        items = null;
    }

    private void recreatePagination() {
        pagination = null;
    }

    public String next() {
        getPagination().nextPage();
        recreateModel();
        return "list";
    }

    public String previous() {
        getPagination().previousPage();
        recreateModel();
        return "list";
    }
    @FacesConverter(forClass = Usuario.class)
    public static class UsuarioControllerConverter implements Converter {

        public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
            if (value == null || value.length() == 0) {
                return null;
            }
            UsuarioController controller = (UsuarioController) facesContext.getApplication().getELResolver().
                    getValue(facesContext.getELContext(), null, "usuarioController");
            //return controller.getJpaController().findUsuario(getKey(value));
            return controller.usuario.getItem(getKey(value));
        }

        java.lang.Integer getKey(String value) {
            java.lang.Integer key;
            key = Integer.valueOf(value);
            return key;
        }

        String getStringKey(java.lang.Integer value) {
            StringBuffer sb = new StringBuffer();
            sb.append(value);
            return sb.toString();
        }

        public String getAsString(FacesContext facesContext, UIComponent component, Object object) {
            if (object == null) {
                return null;
            }
            if (object instanceof Usuario) {
                Usuario o = (Usuario) object;
                return getStringKey(o.getId());
            } else {
                throw new IllegalArgumentException("object " + object + " is of type " + object.getClass().getName() + "; expected type: " + UsuarioController.class.getName());
            }
        }
    }
}
